﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using net8.Helper;
using net8.Models;
using System.Collections.Generic;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace net8.Filter
{
    /// <summary>
    /// 自定义授权过滤器
    /// </summary>
    public class NetAuthorizationFilter : IAsyncAuthorizationFilter
    {
        /// <summary>
        /// 授权处理逻辑
        /// </summary>
        /// <param name="context">授权上下文</param>
        /// <returns></returns>
        public Task OnAuthorizationAsync(AuthorizationFilterContext context)
        {
            if (context.ActionDescriptor.EndpointMetadata.Any(item => item is IAllowAnonymous))
            {
                return Task.CompletedTask;
            }

            List<UserCache> list = CsRedisHelper.Get<List<UserCache>>("UserCache");
            if (context.HttpContext.User.Claims.Any(u => u.Type == "UserId"))
            {
                var userId = context.HttpContext.User.Claims.First(u => u.Type == "UserId").Value;
                var loginId = context.HttpContext.User.Claims.First(u => u.Type == "LoginId").Value;
                UserCache user = list.First(u => u.UserId == Guid.Parse(userId));
                if (user.RoleName.Any(r => r == "网站管理员"))
                {
                    return Task.CompletedTask;
                }
                if (!user.IsEnable)
                {
                    context.Result = new JsonResult(new
                    {
                        Status = 3,
                        Msg = "当前账户已经被禁用"
                    });
                }
                else if (user.LoginId != Guid.Parse(loginId))
                {
                    context.Result = new JsonResult(new
                    {
                        Status = 3,
                        Msg = "已有其他用户在登录，当前token已失效"
                    });
                }
            }

            return Task.CompletedTask;
        }
    }
}
